﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using WWLauncher.Constant;
using WWLauncher.Interface;
using WWLauncher.Util;
using WWLauncher.ViewModel;
using static WWLauncher.Util.ShowWindowFollowMouse;

namespace WWLauncher.View
{
    /// <summary>
    /// 添加系统项目到对应菜单
    /// </summary>
    public partial class SystemItemWindow : Window, IWindowCommon
    {
        private readonly SystemItemViewModel vm;
        private List<IconViewModel> systemIcons;
        private List<IconViewModel> startMenuIcons;
        private List<IconViewModel> storeIcons;

        private SystemItemWindow()
        {
            vm = new SystemItemViewModel();
            this.DataContext = vm;
            InitializeComponent();
            this.Topmost = true;
        }

        private void Window_OnLoaded(object sender, RoutedEventArgs e)
        {
            RunTimeStatus.WpfWindowClick = true;
            RunTimeStatus.WpfWindowOpening = true; 
            
            BGSettingUtil.BGSetting(BGBorder);
        }
        /// <summary>
        /// 移动窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DragMove(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private void CloseBtn_Click(object sender, RoutedEventArgs e)
        {
            this.DataContext = null;
            this.Close();
        }

        /// <summary>
        /// 切换选项卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabItem ti = this.MyTabControl.SelectedItem as TabItem;


            switch (ti.Tag.ToString())
            {
                case "StartMenu": //开始菜单
                    if (startMenuIcons == null)
                    {
                        vm.IconInfos = null;
                        Task.Run(GetStartMenuInfos);
                    }
                    else
                    {
                        StartMenuLoading.Visibility = Visibility.Collapsed;
                        vm.IconInfos = startMenuIcons;
                    }
                    break;
                case "Store": //应用商店
                    if (storeIcons == null)
                    {
                        vm.IconInfos = null;
                        storeIcons = new List<IconViewModel>();
                        vm.IconInfos = storeIcons;
                    }
                    else
                    {
                        vm.IconInfos = storeIcons;
                    }
                    break;
                default: //默认系统项
                    if (systemIcons == null)
                    {
                        vm.IconInfos = null;
                        systemIcons = GetSysteIconInfos();
                        vm.IconInfos = systemIcons;
                    }
                    else
                    {
                        vm.IconInfos = systemIcons;
                    }
                    break;
            }
        }

        /// <summary>
        /// 获取开始菜单路径下项目
        /// </summary>
        /// <returns></returns>
        private void GetStartMenuInfos()
        {
            this.Dispatcher.Invoke(() =>
            {
                StartMenuLoading.Visibility = Visibility.Visible;
            });

            var infos = new List<IconViewModel>();
            //获取开始菜单路径
            string path = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) + "\\Programs";
            //递归获取信息
            GetInfos(path, infos);
            this.Dispatcher.Invoke(() =>
            {
                if (StartMenu.IsSelected)
                {
                    startMenuIcons = infos;
                    vm.IconInfos = startMenuIcons;
                }
                StartMenuLoading.Visibility = Visibility.Collapsed;
            });

        }

        /// <summary>
        /// 递归获取文件信息
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="listInfos"></param>
        private void GetInfos(string filePath, List<IconViewModel> listInfos)
        {
            string[] filePaths = Directory.GetFiles(filePath);
            string[] dirPaths = Directory.GetDirectories(filePath);

            string[] paths = new string[filePaths.Length + dirPaths.Length];
            filePaths.CopyTo(paths, 0);
            if (filePaths.Length == 0)
            {
                dirPaths.CopyTo(paths, 0);
            }
            else
            {
                dirPaths.CopyTo(paths, filePaths.Length - 1);
            }

            foreach (string path in paths)
            {
                if (File.Exists(path))
                {
                    string ext = Path.GetExtension(path).ToLower();
                    if (".exe".Equals(ext) || ".lnk".Equals(ext))
                    {
                        try
                        {
                            var iconInfo = CommonCode.GetIconInfoByPath_NoWrite(path);
                            if (iconInfo.TargetPath != null)
                            {
                                listInfos.Add(iconInfo);
                            }
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                    }
                }
                else if (Directory.Exists(path))
                {
                    GetInfos(path, listInfos);
                }
            }
        }

        /// <summary>
        /// 获取系统项目
        /// </summary>
        /// <returns></returns>
        private List<IconViewModel> GetSysteIconInfos()
        {
            var iconInfos = new List<IconViewModel>();

            foreach (var item in Constants.SystemIcons)
            {
                var iconInfo = new IconViewModel
                {
                    Name = item.Value
                };
                iconInfo.BitmapImage = new BitmapImage(
                        new Uri("pack://application:,,,/Resource/Image/SystemIcon/" + item.Key + ".png"
                        , UriKind.Absolute));
                iconInfo.StartArg = item.Key;
                iconInfo.ToolTip = iconInfo.Name;
                iconInfos.Add(iconInfo);
            }
            return iconInfos;
        }



        private static System.Windows.Window window = null;
        public new static void Show()
        {
            if (window == null || !window.Activate())
            {
                window = new SystemItemWindow();
            }
            window.Show();
            Keyboard.Focus(window);
            ShowWindowFollowMouse.Display(window, MousePosition.Center, 0, 0);
        }


        public void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.DataContext = null;
                this.Close();
            }
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            RunTimeStatus.WpfWindowClick = false;
            RunTimeStatus.WpfWindowOpening = false;
            ConfigUtil.SaveAppData();
        }

    }
}